import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Table, Tag, Button, List, Avatar, Empty, message } from 'antd';
import { 
  UserOutlined, 
  ShoppingOutlined, 
  FileTextOutlined, 
  EyeOutlined,
  PlusOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  TrophyOutlined,
  TeamOutlined,
  CustomerServiceOutlined,
  SafetyOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useProductStore, useCaseStore, useAuthStore } from '../../services/store';
import { statsApi } from '../../services/api';
import { ROUTES } from '../../constants';
import type { Product, Case } from '../../types';

const DashboardPage: React.FC = () => {
  const navigate = useNavigate();
  const { user, isAuthenticated, checkAuth } = useAuthStore();
  const { products, fetchProducts } = useProductStore();
  const { cases, fetchCases } = useCaseStore();
  const [loading, setLoading] = useState(true);
  const [dashboardStats, setDashboardStats] = useState<any>(null);

  useEffect(() => {
    const initAuth = async () => {
      if (!isAuthenticated) {
        await checkAuth();
      }
    };
    initAuth();
  }, [isAuthenticated, checkAuth]);

  useEffect(() => {
    const loadData = async () => {
      // 检查用户是否已认证且有管理员权限
      if (!isAuthenticated || !user) {
        message.error('请先登录');
        navigate('/login');
        return;
      }
      
      if (user.role !== 'admin') {
        message.error('权限不足，需要管理员权限');
        navigate('/');
        return;
      }

      // 检查token是否存在
      const token = localStorage.getItem('auth_token');
      if (!token) {
        message.error('登录已过期，请重新登录');
        navigate('/login');
        return;
      }

      setLoading(true);
      try {
        const [stats] = await Promise.all([
          statsApi.getDashboardStats(),
          fetchProducts({ pageSize: 10 }),
          fetchCases({ pageSize: 10 })
        ]);
        setDashboardStats(stats);
      } catch (error) {
        console.error('加载数据失败:', error);
        if (error instanceof Error && (error.message.includes('认证') || error.message.includes('登录'))) {
          message.error('登录已过期，请重新登录');
          // 清除无效token
          localStorage.removeItem('auth_token');
          navigate('/login');
        } else {
          message.error('加载数据失败，请重试');
        }
      } finally {
        setLoading(false);
      }
    };
    
    if (isAuthenticated && user) {
      loadData();
    }
  }, [fetchProducts, fetchCases, isAuthenticated, user, navigate]);

  // 统计数据
  const stats = [
    {
      title: '总产品数',
      value: dashboardStats?.totalProducts || 0,
      prefix: <ShoppingOutlined />,
      suffix: '个',
      trend: 'up',
      trendValue: dashboardStats?.monthlyStats?.products || 0
    },
    {
      title: '总案例数',
      value: dashboardStats?.totalCases || 0,
      prefix: <FileTextOutlined />,
      suffix: '个',
      trend: 'up',
      trendValue: dashboardStats?.monthlyStats?.cases || 0
    },
    {
      title: '本月访问量',
      value: dashboardStats?.totalViews || 0,
      prefix: <EyeOutlined />,
      suffix: '次',
      trend: 'up',
      trendValue: dashboardStats?.monthlyStats?.views || 0
    },
    {
      title: '总用户数',
      value: dashboardStats?.totalUsers || 0,
      prefix: <UserOutlined />,
      suffix: '个',
      trend: 'up',
      trendValue: 0
    }
  ];

  // 最新产品
  const recentProducts = dashboardStats?.recentProducts?.map((product: any) => ({
    key: product.id,
    name: product.name,
    category: product.category,
    status: 'published',
    createdAt: product.createdAt
  })) || [];

  // 最新案例
  const recentCases = dashboardStats?.recentCases?.map((caseItem: any) => ({
    key: caseItem.id,
    title: caseItem.title,
    client: caseItem.client,
    industry: caseItem.category,
    status: 'published',
    createdAt: caseItem.createdAt
  })) || [];

  // 快捷操作
  const quickActions = [
    {
      title: '新增产品',
      description: '添加新的产品或服务',
      icon: <PlusOutlined />,
      color: '#1677FF',
      action: () => navigate(ROUTES.ADMIN.PRODUCTS, { state: { action: 'create' } })
    },
    {
      title: '新增案例',
      description: '添加新的成功案例',
      icon: <PlusOutlined />,
      color: '#52C41A',
      action: () => navigate(ROUTES.ADMIN.CASES, { state: { action: 'create' } })
    },
    {
      title: '查看产品',
      description: '管理所有产品信息',
      icon: <ShoppingOutlined />,
      color: '#FA8C16',
      action: () => navigate(ROUTES.ADMIN.PRODUCTS)
    },
    {
      title: '查看案例',
      description: '管理所有案例信息',
      icon: <FileTextOutlined />,
      color: '#722ED1',
      action: () => navigate('/admin/cases')
    }
  ];



  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 欢迎信息 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">
          欢迎回来，{user?.username || '管理员'}！
        </h1>
        <p className="text-gray-600">
          今天是 {new Date().toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            weekday: 'long'
          })}
        </p>
      </div>

      {/* 数据统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        {stats.map((stat, index) => (
          <Col xs={24} sm={12} lg={6} key={index}>
            <Card className="card-hover">
              <Statistic
                title={stat.title}
                value={stat.value}
                prefix={stat.prefix}
                suffix={stat.suffix}
                valueStyle={{ color: '#1677FF' }}
              />
              <div className="flex items-center mt-2 text-sm">
                {stat.trend === 'up' ? (
                  <ArrowUpOutlined className="text-green-500 mr-1" />
                ) : (
                  <ArrowDownOutlined className="text-red-500 mr-1" />
                )}
                <span className={stat.trend === 'up' ? 'text-green-500' : 'text-red-500'}>
                  {stat.trendValue}%
                </span>
                <span className="text-gray-500 ml-1">较上月</span>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 两行两列布局 */}
      <Row gutter={[16, 16]}>
        {/* 第一行 */}
        <Col xs={24} lg={12}>
          {/* 快捷操作 */}
          <Card title="快捷操作" className="mb-4 card-hover" style={{ height: '300px' }}>
            <Row gutter={[16, 16]}>
              {quickActions.map((action, index) => (
                <Col xs={12} sm={12} key={index}>
                  <Card 
                    hoverable
                    className="text-center cursor-pointer"
                    styles={{ body: { padding: '16px' } }}
                    onClick={action.action}
                  >
                    <div 
                      className="text-2xl mb-2"
                      style={{ color: action.color }}
                    >
                      {action.icon}
                    </div>
                    <div className="font-medium text-sm">{action.title}</div>
                    <div className="text-xs text-gray-500 mt-1">
                      {action.description}
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          {/* 本月统计 */}
          <Card title="本月统计" className="mb-4 card-hover" style={{ height: '300px' }}>
            {dashboardStats?.monthlyStats ? (
              <div className="space-y-4">
                <div className="flex justify-between items-center p-3 bg-blue-50 rounded">
                  <span className="text-gray-600 font-medium">新增产品</span>
                  <span className="font-bold text-xl text-blue-600">{dashboardStats.monthlyStats.products}</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-green-50 rounded">
                  <span className="text-gray-600 font-medium">新增案例</span>
                  <span className="font-bold text-xl text-green-600">{dashboardStats.monthlyStats.cases}</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-purple-50 rounded">
                  <span className="text-gray-600 font-medium">页面访问</span>
                  <span className="font-bold text-xl text-purple-600">{dashboardStats.monthlyStats.views}</span>
                </div>
              </div>
            ) : (
              <Empty description="暂无统计数据" />
            )}
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[16, 16]}>
        {/* 第二行 */}
        <Col xs={24} lg={12}>
          {/* 最新产品 */}
          <Card 
            title="最新产品" 
            className="card-hover"
            style={{ height: '400px' }}
            extra={
              <Button 
                type="link" 
                onClick={() => navigate('/admin/products')}
              >
                查看全部
              </Button>
            }
          >
            <Table
              dataSource={recentProducts}
              pagination={false}
              size="small"
              loading={loading}
              scroll={{ y: 280 }}
              locale={{
                emptyText: <Empty description="暂无产品数据" />
              }}
              columns={[
                {
                  title: '产品名称',
                  dataIndex: 'name',
                  key: 'name',
                  ellipsis: true
                },
                {
                  title: '分类',
                  dataIndex: 'category',
                  key: 'category',
                  width: 100,
                  render: (category) => (
                    <Tag color="blue">{category || '未分类'}</Tag>
                  )
                },
                {
                  title: '创建时间',
                  dataIndex: 'createdAt',
                  key: 'createdAt',
                  width: 100,
                  render: (date) => formatDate(date)
                }
              ]}
            />
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          {/* 最新案例 */}
          <Card 
            title="最新案例" 
            className="card-hover"
            style={{ height: '400px' }}
            extra={
              <Button 
                type="link" 
                onClick={() => navigate('/admin/cases')}
              >
                查看全部
              </Button>
            }
          >
            <Table
              dataSource={recentCases}
              pagination={false}
              size="small"
              loading={loading}
              scroll={{ y: 280 }}
              locale={{
                emptyText: <Empty description="暂无案例数据" />
              }}
              columns={[
                {
                  title: '案例标题',
                  dataIndex: 'title',
                  key: 'title',
                  ellipsis: true
                },
                {
                  title: '客户',
                  dataIndex: 'client',
                  key: 'client',
                  width: 120,
                  ellipsis: true
                },
                {
                  title: '行业',
                  dataIndex: 'industry',
                  key: 'industry',
                  width: 100,
                  render: (industry) => (
                    <Tag color="purple">{industry || '未分类'}</Tag>
                  )
                },
                {
                  title: '创建时间',
                  dataIndex: 'createdAt',
                  key: 'createdAt',
                  width: 100,
                  render: (date) => formatDate(date)
                }
              ]}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default DashboardPage;